package com.zdlyh.controller;

import com.zdlyh.domain.ResponseResult;
import com.zdlyh.domain.entity.LoginUser;
import com.zdlyh.domain.entity.Menu;
import com.zdlyh.domain.entity.User;
import com.zdlyh.enums.AppHttpCodeEnum;
import com.zdlyh.exception.SystemException;
import com.zdlyh.service.AdminLoginService;
import com.zdlyh.service.MenuService;
import com.zdlyh.service.RoleService;
import com.zdlyh.utils.BeanCopyUtils;
import com.zdlyh.utils.SecurityUtils;
import com.zdlyh.domain.vo.AdminUserInfoVo;
import com.zdlyh.domain.vo.RoutersVo;
import com.zdlyh.domain.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AdminLoginController {
    @Autowired
    private AdminLoginService adminLoginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        // 先判断传进来的用户名是否为空
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return adminLoginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
        // 获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = SecurityUtils.getUserId();
        // 根据id查询用户权限信息
        List<String> perms = menuService.getPermsByUserId(userId);

        // 根据id查询用户角色信息
        List<String> roleKeys = roleService.getRoleKeyByUserId(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(),UserInfoVo.class);
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeys,userInfoVo);

        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        Long userId = SecurityUtils.getUserId();
        List<Menu> menus = menuService.getRouterMenuTreeByUserId(userId);
        return ResponseResult.okResult(new RoutersVo(menus));
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return adminLoginService.logout();
    }

}
